package cn.cheln.support.mobile.root;

import java.io.DataOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 13-10-14.
 */
public class Root {
    public static Boolean mHasRoot = null;

    public static int execRootCmdSilent(String cmd) {
        int result = -1;
        DataOutputStream dos = null;

        try {
            Process p = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(p.getOutputStream());

            dos.writeBytes(cmd + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();
            p.waitFor();
            result = p.exitValue();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static boolean haveRoot() {
        if(mHasRoot==null){
            mHasRoot = rootExec("echo test").equals("");
        }
        return mHasRoot;
    }

    public static String rootExec(String cmd) {

        Process process = null;

        DataOutputStream os = null;
        StringBuilder sb;
        try {

            process = Runtime.getRuntime().exec("su"); //切换到root帐号
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(cmd + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            return "e";
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
            }

        }

        return "";

    }

}
